/* 
    动态网站
*/

const http = require("http");
const path = require("path");
const fs = require("fs");
const querystring = require("querystring");
const scoreData = require("./scores.json");


http.createServer((req, res) => {
    // 查询
    if (req.url.startsWith("/query") && req.method == "GET") {
        fs.readFile(
            path.join(__dirname, "view", "index.html"),
            "utf8",
            (err, content) => {
                if (err) {
                    res.write(500, {
                        "Content-Type": "text/plain; charset=utf8"
                    });
                    res.end("服务器出错，请联系管理员");
                }
                res.end(content);
            }
        );
    } else if (req.url.startsWith("/score") && req.method == "POST") {
        // 获取成绩结果 /score
        let dpata = '';
        req.on('data', (chunk) => {
            dpata += chunk;
        });
        req.on('end', () => {
            let obj = querystring.parse(dpata);
            let result = scoreData[obj.code];
            fs.readFile(path.join(__dirname, 'view', 'result.html'), 'utf8', (err, content) => {
                if (err) {
                    res.write(500, {
                        "Content-Type": "text/plain; charset=utf8"
                    });
                    res.end('服务器错误，请联系管理员');
                }
                content = content.replace("$$chinese$$", result.chinese);
                content = content.replace("$$math$$", result.math);
                content = content.replace("$$english$$", result.english);
                content = content.replace("$$summary$$", result.summary);

                res.end(content);

            });
        });
    }
})
    .listen(3000, () => {
        console.log("running……");
    });
